package com.j2009.springbootproject.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j2009.springbootproject.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * ClassName: JWTInterceptor
 * Description:
 * date: 2021/4/6 16:26
 *
 * @author wuyafeng
 * @version 1.0   softeem.com
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //允许跨域请求
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","GET,POST");

        //如果请求是 /user/login 直接通过 (解决拦截器放行不生效)
        if(request.getRequestURI().contains("user/login")){
            return true;
        }

        HashMap<String,Object> map = new HashMap<>();
        //建议将token放在请求头中
//        获取请求头中的令牌
        String token = request.getHeader("token");
    try {
        JWTUtils.verify(token);
        return true;
    }catch(SignatureVerificationException e){
        e.printStackTrace();
        map.put("msg","无效的签名");
    }catch (TokenExpiredException e){
        e.printStackTrace();
        map.put("msg","签名已过期");
    }catch(AlgorithmMismatchException e){
        e.printStackTrace();
        map.put("msg","签名算法不一致");
    }catch (Exception e){
        e.printStackTrace();
        map.put("msg","token无效");
    }

     map.put("state",false);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
